package com.efounder.chat.activity;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.efounder.chat.R;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.RequestHttpDataUtil;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.util.CloudUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.UriUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

public class RegisterByRestFulActivity extends Activity implements OnClickListener {

    private String nickName;
    private String avatar;
    private String userName;
    private String userPassWord;
    private String userPassWordConfirm;
    private String sex;
    private ImageView iv_hideImage;
    private ImageView iv_showImage;
    private EditText et_userPassWord;
    private EditText et_userPassWord_confirm;
    private ImageView iv_avater;
    private EditText et_userName;
    private TextView tv_total;

    private String picturePath;//图片在相册中的路径
    private String pictureUrlPath;//图片在网络上的路径
    private String imageName;//图片名称
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final int UPDATE_FXID = 4;// 结果
    private static final int UPDATE_NICK = 5;// 结果

    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.fragment_register);

        ImageView iv_backImage = (ImageView) findViewById(R.id.iv_back);
        iv_backImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterByRestFulActivity.this.finish();
            }
        });
        tv_total = (TextView)findViewById(R.id.tv_title);
        tv_total.setText(R.string.wrchatview_registered);

        iv_avater = (ImageView) findViewById(R.id.iv_photo);
        iv_avater.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 打开系统相册，选择头像
//                int PICTURE = 0;
//                Intent picture = new Intent(Intent.ACTION_PICK, android.provider.MediaStore
//                        .Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(picture, PICTURE);
                getNowTime();
                imageName = getNowTime() + ".png";
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
            }
        });

        et_userName = (EditText) findViewById(R.id.et_username);
        et_userPassWord = (EditText) findViewById(R.id.et_password);
        et_userPassWord_confirm = (EditText) findViewById(R.id.et_password_corfirm);

        String usernamestring = getIntent().getStringExtra("userName");
        String passwordstring = getIntent().getStringExtra("password");


        if (usernamestring != null && !"".equals(usernamestring)) {
            et_userName.setText(usernamestring);
        }
        if (passwordstring != null && !"".equals(passwordstring)) {
            et_userPassWord.setText(passwordstring);
        }

        Button btn = (Button) findViewById(R.id.btn_register);
        iv_hideImage = (ImageView) findViewById(R.id.iv_hide);
        iv_showImage = (ImageView) findViewById(R.id.iv_show);

        iv_hideImage.setOnClickListener(this);
        iv_showImage.setOnClickListener(this);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et_nickName = (EditText) findViewById(R.id.et_usernick);
                RadioButton rb_sex = (RadioButton) findViewById(R.id.rb_male);

                nickName = et_nickName.getText().toString();
                avatar = iv_avater.getDrawable().toString();
                userName = et_userName.getText().toString();
                userPassWord = et_userPassWord.getText().toString();
                userPassWordConfirm = et_userPassWord_confirm.getText().toString();
                sex = rb_sex.isChecked() ? "男" : "女";

                if ((nickName == null || "".equals(nickName.trim())) || (userName == null || ""
                        .equals(userName.trim())) || (userPassWord == null || "".equals
                        (userPassWord.trim())) || (userPassWordConfirm == null || "".equals
                        (userPassWordConfirm.trim()))) {
                    Toast.makeText(RegisterByRestFulActivity.this, R.string.wrchatview_nickname_registered, Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                if (!userPassWord.equals(userPassWordConfirm)) {
                    Toast.makeText(RegisterByRestFulActivity.this, R.string.wrchatview_password_not_same, Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                final ProgressDialog dialog = new ProgressDialog(RegisterByRestFulActivity.this);
                dialog.setMessage(ResStringUtil.getString(R.string.wrchatview_registering));
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();
                GetHttpUtil.signByRestFul(RegisterByRestFulActivity.this, userName, nickName, userPassWord, pictureUrlPath, sex, new RequestHttpDataUtil.SignByRestFulCallBack() {
                    @Override
                    public void signResponse(int responsenum, String response) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                       // {"result":"success","user":{"imUserId":3275,"imUserPassWord":"123456","passWord":"PNcxc`x^9l`i41^9l^ifcc7i1`5z07","userId":"95598","userName":"åº·æ\u0095°æ\u008D®"}}
                       // {"result":"fail","msg":"用户已经存在"}
                        if(responsenum == 0){

                            JSONObject jsonObject = JSON.parseObject(response);
                            String result = "";
                            if (EnvironmentVariable.getProperty("APPID").equals("OSPMobileSD") ||
                                    EnvironmentVariable.getProperty("APPID").equals("OSPMobileSDTest")) {
                                result = jsonObject.getString("status");
                            }else {
                                result = jsonObject.getString("result");
                            }
                            if("success".equals(result)){
                                Toast.makeText(RegisterByRestFulActivity.this, R.string.wrchatview_registered_success, Toast.LENGTH_LONG).show();
                                Intent intent = getIntent();
                                intent.putExtra("name", userName);
                                intent.putExtra("password", userPassWord);
                                setResult(RESULT_OK, intent);
                                RegisterByRestFulActivity.this.finish();
                            }else{
                                String msg =  jsonObject.getString("msg");
                                Toast.makeText(RegisterByRestFulActivity.this,msg, Toast
                                        .LENGTH_LONG).show();
                            }

                        }else if(responsenum == 1){
                            //网络出错

                            Toast.makeText(RegisterByRestFulActivity.this, R.string.wrchatview_server_request_fail, Toast
                                    .LENGTH_LONG).show();
                        }else if(responsenum == 2){
                            //未设置注册地址
                            Toast.makeText(RegisterByRestFulActivity.this, R.string.wrchatview_not_set_register_address, Toast
                                    .LENGTH_LONG).show();
                        }
                    }
                });



//                PO.SetValueByParamName("method", "sign");
//                PO.SetValueByParamName("userName", userName);
//                PO.SetValueByParamName("userPassWord", userPassWord);
//                PO.SetValueByParamName("nikeName", nickName);
//                PO.SetValueByParamName("sex", sex);
//                PO.SetValueByParamName("APPID", EnvironmentVariable.getProperty("APPID"));
//                PO.SetValueByParamName("avatar", pictureUrlPath);
//
//                new AsyncTask<String, Integer, String>() {
//                    private ProgressDialog dialog;
//
//                    @Override
//                    protected void onPreExecute() {
//                        dialog = new ProgressDialog(RegisterByRestFulActivity.this);
//                        dialog.setMessage("正在注册...");
//                        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                        dialog.show();
//                        super.onPreExecute();
//                    }
//
//                    @Override
//                    protected String doInBackground(String... params) {
//                        //调用后台接口，注册
//                        try {
//                            //连接服务器
//                            String serverKey = EnvironmentVariable.getProperty("ServerKey");
//                            JResponseObject RO = EAI.DAL.SVR(serverKey, PO);
//                            //解析RO，是否注册成功
//                            if (RO == null) {
//                                return "RO_NULL";
//                            } else {
//                                EFDataSet dataSet = (EFDataSet) RO.getResponseObject();
//                                if (dataSet.getRowCount() <= 0) {
//                                    return "RO_NULL";
//                                }
//                                EFRowSet rowSet = dataSet.getRowSet(0);
//                                Map<String, Object> map = new HashMap<String, Object>();
//                                map = rowSet.getDataMap();
//                                String result = (String) map.get("tip");
//                                return result;
//                            }
//
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            return "error";
//                        }
//                    }
//
//                    @Override
//                    protected void onPostExecute(String result) {
//                        if (dialog.isShowing()) {
//
//                            dialog.dismiss();
//                        }
//                        if ("注册成功".equals(result)) {
//                            Toast.makeText(RegisterByRestFulActivity.this, "注册成功,请登录。", Toast.LENGTH_LONG).show();
//                            Intent intent = getIntent();
//                            intent.putExtra("name", userName);
//                            intent.putExtra("password", userPassWord);
//                            setResult(RESULT_OK, intent);
//                            RegisterByRestFulActivity.this.finish();
//                        }
//                        if ("您已注册。".equals(result)) {
//                            Toast.makeText(RegisterByRestFulActivity.this, "您已注册，请直接登陆。", Toast
//                                    .LENGTH_LONG).show();
//                            return;
//                        }
//                        if ("RO_NULL".equals(result)) {
//                            Toast.makeText(RegisterByRestFulActivity.this, "服务器请求失败，请稍后再试。", Toast
//                                    .LENGTH_LONG).show();
//                            return;
//                        }
//                        if ("error".equals(result)) {
//                            Toast.makeText(RegisterByRestFulActivity.this, "应用程序出错，请联系技术人员。", Toast
//                                    .LENGTH_LONG).show();
//                            return;
//                        }
//                    }
//                }.execute();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.iv_hide) {
            iv_hideImage.setVisibility(ImageView.INVISIBLE);
            iv_showImage.setVisibility(ImageView.VISIBLE);
            et_userPassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            iv_hideImage.setVisibility(ImageView.VISIBLE);
            iv_showImage.setVisibility(ImageView.INVISIBLE);
            et_userPassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0 && resultCode == Activity.RESULT_OK && null != data) {
//            Uri selectedImage = data.getData();
//            cropRawPhoto(selectedImage);
//            String[] filePathColumns = {MediaStore.Images.Media.DATA};
//            Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,
//                    null, null);
//            c.moveToFirst();
//            int columnIndex = c.getColumnIndex(filePathColumns[0]);
//            picturePath = c.getString(columnIndex);
//            c.close();
////	      //获取图片并显示
//            // iv_avater.setImageURI(selectedImage);
//        } else if (requestCode == 1 && null != data && resultCode == Activity.RESULT_OK) {
//                Bundle extras = data.getExtras();
//                if (extras != null) {
//                    Bitmap photo = extras.getParcelable("data");
//                    iv_avater.setImageBitmap(photo);
//                    File file = new File(picturePath);
//                    if (file.exists()) {
//                        try {
//                            ImageUtil.saveFile(photo, file.getName());
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                        String avatarPath = ImageUtil.chatpath + ImageUtil.
//                                getFileName(ImageUtil.chatpath + file.getName() + ".pic");
//                        Log.i("剪裁后头像文件路径：", avatarPath);
//                        QiNiuUtil.getQiNiuRes(avatarPath, new QiNiuUtil.UpLoadListener() {
//                            @Override
//                            public void getHttpUrl(Boolean isSuccess, String url) {
//                                if (isSuccess) {
//                                    Log.i("RegisterActivity", "---头像在七牛服务器上的路径:" + url);
//                                    pictureUrlPath = url;
//                                } else {
//                                    pictureUrlPath = "http://oap8mw8pg.bkt.clouddn" +
//                                            ".com/FpDdVce3uiMlxVTY0IGDWYnZosUZ";
//                                }
//
//                            }
//                        });
//                    }
//
//                }
//            }
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    new PictureAndCropManager(this).startPhotoZoom(
                            UriUtils.getUriForFile((new File(ImageUtil.chatpath, imageName))),
                            480);
                    picturePath = ImageUtil.chatpath + imageName;

                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null)
                        new PictureAndCropManager(this).startPhotoZoom(data.getData(), 480);
                    break;

                case PHOTO_REQUEST_CUT:
                    Bitmap bitmap = BitmapFactory.decodeFile(ImageUtil.chatpath
                            + imageName);

                    // File file = new File(picturePath);
                    //  if (file.exists()) {
                    try {
                        ImageUtil.saveFile(bitmap, imageName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String avatarPath = ImageUtil.chatpath + ImageUtil.
                            getFileName(ImageUtil.chatpath + imageName + ".pic");
                    final Bitmap bitmap1 = BitmapFactory.decodeFile(ImageUtil.chatpath
                            + imageName + ".pic");

                    Log.i("剪裁后头像文件路径：", avatarPath);
                    if (!isNetActive()) {
                        ToastUtil
                                .showToast(RegisterByRestFulActivity.this, R.string.wrchatview_online_error_please);
                        return;
                    }



                    CloudUtil.getCloudRes(avatarPath, new CloudUtil.UpLoadListenerWithProgress() {
                        @Override
                        public void getHttpUrl(Boolean isSuccess, String url) {
                            if (isSuccess) {
                                pictureUrlPath = url;
                                pictureUrlPath.trim();
                            } else {
                                pictureUrlPath = "";
                            }
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    iv_avater.setImageBitmap(bitmap1);
                                }
                            });
                        }

                        @Override
                        public void getHttpProgress(int progress) {

                        }
                    });
//                    try {
//                        //todo 普联云盘上传
//                        PansoftCloudUtil.getCloudRes(avatarPath, new PansoftCloudUtil.UpLoadListener() {
//                            @Override
//                            public void getHttpUrl(Boolean isSuccess, String url) {
//                                if (isSuccess) {
//
//                                    Log.i("RegisterActivity", "---头像在普联云盘服务器上的路径:" + url);
//                                    pictureUrlPath = url;
//                                    pictureUrlPath.trim();
//
//
//                                } else {
//                                    pictureUrlPath = "http://oap8mw8pg.bkt.clouddn" +
//                                            ".com/FpDdVce3uiMlxVTY0IGDWYnZosUZ";
//
//                                }
//                            }
//                        });
//                        //todo 七牛上传
//
////                        QiNiuUtil.getQiNiuRes(avatarPath, new QiNiuUtil.UpLoadListener() {
////                            @Override
////                            public void getHttpUrl(Boolean isSuccess, String url) {
////                                if (isSuccess) {
////
////                                    Log.i("RegisterActivity", "---头像在七牛服务器上的路径:" + url);
////                                    pictureUrlPath = url;
////                                    pictureUrlPath.trim();
////
////
////                                } else {
////                                    pictureUrlPath = "http://oap8mw8pg.bkt.clouddn" +
////                                            ".com/FpDdVce3uiMlxVTY0IGDWYnZosUZ";
////
////                                }
////
////                            }
////                        });
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    // }



                    break;

            }
            super.onActivityResult(requestCode, resultCode, data);

        }
    }

    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
        return dateFormat.format(date);
    }

}
